from django.core.management.base import BaseCommand

from django.conf import settings

from email.mime.text import MIMEText
from email.utils import formataddr

from z_import.cons import send_to_email
from z_import.cons import smpt_port, smpt_email
from z_import.cons import end_row, start_row

import smtplib


class Command(BaseCommand):
    help = '发送邮件, 内容包括-初始密码'

    def add_arguments(self, parser):
        parser.add_argument('-f',
                            '--filename',
                            required=True,
                            help='文件路径(绝对路径)')
        parser.add_argument('-s',
                            '--start_row',
                            default=start_row,
                            required=False,
                            help='起始行')
        parser.add_argument('-e',
                            '--end_row',
                            default=end_row,
                            required=False,
                            help='终止行')

    def analysis(self, sheet_one, cur_row):

        email_col = 'G'

        email = sheet_one['{}{}'.format(email_col, cur_row)].value

        if email:
            send_to_email.append(email)

    def send_email(self, send_to_email):
        msg = MIMEText('初始密码: %s' % settings.BEGIN_PASS, 'plain', 'utf-8')

        msg['From'] = formataddr(['临床流调系统', settings.EMAIL_HOST_USER])

        msg['To'] = formataddr(['来源', settings.EMAIL_HOST_USER])

        msg['Subject'] = '临床流调系统'

        try:
            server = smtplib.SMTP(smpt_email, smpt_port)

            server.login(settings.EMAIL_HOST_USER, settings.EMAIL_HOST_PASSWORD)

            server.sendmail(settings.EMAIL_HOST_USER, send_to_email, msg.as_string())
        except Exception as e:

            self.stdout.write(self.style.SUCCESS('发送邮箱失败原因: %s' % e))
        else:
            server.quit()

        self.stdout.write(self.style.SUCCESS('邮件发送成功'))

    def handle(self, *args, **options):
        filename = options.get('filename')
        start_row_param = int(options.get('start_row'))
        end_row_param = int(options.get('end_row'))

        import openpyxl

        wb = openpyxl.load_workbook(filename)

        sheetsname = wb.sheetnames

        # 只有一个表格的情况下
        sheet_one = wb[sheetsname[0]]

        for cur_row in range(start_row_param, end_row_param + 1):
            self.analysis(sheet_one, cur_row)

        self.stdout.write(self.style.SUCCESS('表格中存在邮箱个数有: %d 个' % len(send_to_email)))

        self.send_email(send_to_email)
